package org.example.easybuy.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.easybuy.entity.CollectionBox;
import org.example.easybuy.service.CollectionBoxService;
import org.example.easybuy.util.CustomResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class CollectionBoxController {

    @Autowired
    private CollectionBoxService collectionBoxService;

    ObjectMapper objectMapper=new ObjectMapper();
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/intoCollectionBox")
    public CustomResult intoCollectionBox(@RequestParam Map<String,String> map) throws JsonProcessingException {
        String msg=collectionBoxService.intoCollectionBox(map);
        return CustomResult.successResult().addResult("isAdd",msg);
    }

    @GetMapping("/getCollectionBox")
    public CustomResult getCollectionBox(String loginName) throws JsonProcessingException {
        //获取收藏夹集合
        List<CollectionBox> list=null;
        if(stringRedisTemplate.hasKey(loginName+"_collect"))
        {
            list=objectMapper.readValue(stringRedisTemplate.opsForValue().get(loginName+"_collect"),
                    objectMapper.getTypeFactory().constructCollectionType(List.class, CollectionBox.class));
        }
        return CustomResult.successResult().addResult("collectionBox",list);
    }

    @GetMapping("/delCollectById")
    public CustomResult delCollectById(int id,String loginName) throws JsonProcessingException {
        if(collectionBoxService.delCollectById(id,loginName))
        {
            return CustomResult.successResult().addResult("isDel","yes");
        }
        return CustomResult.successResult().addResult("isDel","no");
    }
}
